// sugarfreeDirectives.directive('loginDialog', function (AUTH_EVENTS) {
//   return {
//     restrict: 'A',
//     template: '<div ng-if="visible" ng-include="\'partials/login-form.html\'">',
//     link: function (scope) {
//       var showDialog = function () {
//         scope.visible = true;
//       };
  
//       scope.visible = false;
//       scope.$on(AUTH_EVENTS.notAuthenticated, showDialog);
//       scope.$on(AUTH_EVENTS.sessionTimeout, showDialog)
//     }
//   };
// });

sugarfreeDirectives.directive('formAutofillFix',['$timeout',function ($timeout) {
  return function (scope, element, attrs) {
    element.prop('method', 'post');
    if (attrs.ngSubmit) {
      $timeout(function () {
        element
          .unbind('submit')
          .bind('submit', function (event) {
            event.preventDefault();
            element
              .find('input, textarea, select')
              .trigger('input')
              .trigger('change')
              .trigger('keydown');
            scope.$apply(attrs.ngSubmit);
          });
      });
    }
  };
}]);

//directive
sugarfreeDirectives.directive('offEditConfirm',['Utils','$log',function(utils,$log){
	  var log = false;
	  return {
		  restrict:'AE',
		  replace:true,
		  scope:{
			  content:'@',//No use
			  infoName:'@',
			  optConfirm:'&',
			  optCancel:'&'
		  },
		  //template:"<div><div>确定取消编辑吗？</div><div><button class='btn btn-default' ng-click='optConfirm()'>确定</button><button class='btn btn-default' ng-click='offEditForm=false'>取消</button></div></div>",
		  templateUrl:'sf-confirm/offEdit.html',
		  transclude:true,
		  link:function(scope,iElement,iAttrs){
			  if(log){
				  $log.info("scope",scope);
				  $log.info("iElement",iElement);
				  $log.info("iAttrs",iAttrs);
			  }
		  }
	  };
}]);

sugarfreeDirectives.directive('deleteConfirm',['Utils','$log',function(utils,$log){
	  var log = false;
	  return {
		  restrict:'AE',
		  replace:true,
		  scope:{
			  content:'@',//No use
			  infoName:'@',
			  optConfirm:'&',
			  optCancel:'&'
		  },
		  //template:"<div><div>确定取消编辑吗？</div><div><button class='btn btn-default' ng-click='optConfirm()'>确定</button><button class='btn btn-default' ng-click='offEditForm=false'>取消</button></div></div>",
		  templateUrl:'sf-confirm/delete.html',
		  transclude:true,
		  link:function(scope,iElement,iAttrs){
			  if(log){
				  $log.info("scope",scope);
				  $log.info("iElement",iElement);
				  $log.info("iAttrs",iAttrs);
			  }
		  }
	  };
}]);


sugarfreeDirectives.constant('QINIU',{
	domain:'http://7xlk50.com2.z0.glb.qiniucdn.com/'
});

sugarfreeServices.constant('USER_ROLES', {
  all: '*',
  admin: 'admin',
  editor: 'editor',
  guest: 'guest'
});

sugarfreeDirectives.directive('qiniuUpload',['$timeout','$log',function($timeout,$log){
	var log = false;
	return {
		restrict:'AE',
		replace:true,
		scope:{
			//uptokenUrl:'@',
			files:'='
		},
		//templateUrl:'sf-template/process.html',
		link:function(scope,iElement,iAttrs){
			 //console.info(iAttrs);
			 if(log){
				  $log.info("scope",scope);
				  $log.info("iElement",iElement);
				  $log.info("iAttrs",iAttrs);
			 }
			 var pickfiles =  iAttrs.id;
			 var uptokenUrl = iAttrs.uptokenUrl;
			 var uptoken = iAttrs.uptoken;
			 var uploader;
				 if(!uploader){
						var qiniu = new QiniuJsSDK();				 	
				 		uploader = qiniu.uploader({
					  runtimes: 'html5,html4',
					  browse_button: pickfiles,
					  container: "container",
					  //drop_element: 'container',
					  max_file_size: '10mb',
					  // flash_swf_url: 'js/plupload/Moxie.swf',
					  dragdrop: false,
					  chunk_size: '4mb',
					  uptoken_url: uptokenUrl,
					  uptoken:uptoken,
					  domain: 'http://qiniu-plupload.qiniudn.com/',
					  save_key: true,
					  auto_start: true,
					  init: {
						  'FilesAdded': function(up, files) {
							 	console.log("FilesAdded");
						  },
						  'BeforeUpload': function(up, file) {
							  console.log("BeforeUpload");
						  },
						  'UploadProgress': function(up, file) {
							  console.log('UploadProgress',up,file);
						  },
						  'UploadComplete': function() {
							  console.log('UploadComplete');
						  },
						  'FileUploaded': function(up, file, info) {
						  	console.error("up",up);
						  	console.error("file",file);
						  	console.error("info",info);
								scope.$apply(function(){
									var _info = JSON.parse(info);
						  		_info.id = file.id;
									scope.files.push(angular.copy(_info));
								});
								console.info("scope.files",scope.files);
						  },
						  'Error': function(up, err, errTip) {
							  console.log('Error');
							  console.info('err',err,errTip);
							  if(err.code===-600){
							  	alert('上传图片出错！请上传小于10M的图片');
							  }else{
							  	alert('上传图片出错！');
							  }
						  },
						  'Key': function(up, file) {
					            var key = key;
					            // do something with key here
					            return key;
					        }
					  }
				  });
				 }
		}
	};
}]);


sugarfreeDirectives.directive('parcloseProcess',['Utils','$log',function(utils,$log){
	var log = false;
	return {
		restrict:'AE',
		replace:true,
		scope:{
			processText:'@',//No use
			processImage:'@'
		},
		templateUrl:'sf-template/process.html',
		link:function(scope,iElement,iAttrs){
			 if(log){
				  $log.info("scope",scope);
				  $log.info("iElement",iElement);
				  $log.info("iAttrs",iAttrs);
			 }
		}
	};
}]);


sugarfreeApp.directive('sfDatePicker',['$log',function($log) {
	var log = true;
	return {
		restrict:'AE',
		replace:true,
		//require:'?ngModel',
		scope:{
			format:'@',
			startView:'@',
			minView:'@'
		},
		link:function(scope,element,attrs){
//			console.info("scope",scope);
//			console.info("element",element);
//			console.info("attrs",attrs);
//			console.info("ngModel",ngModel);
			scope.format = scope.format || 'yyyy-mm-dd';
			scope.startView = scope.startView || 2;
			scope.minView = scope.minView || 2;
//			console.info('scope.format',scope.format);
//			console.info('scope.startView ',scope.startView );
//			console.info('scope.minView',scope.minView);
			var datePicker = element.datetimepicker({
				 language:'zh-CN',
	    	 format: scope.format,
	    	 todayHighlight: 1,
	    	 startView:parseInt(scope.startView),
	    	 minView:parseInt(scope.minView),
	    	 autoclose:1,
	    	 bootcssVer:3
				});
				
//			var datePicker = element.datetimepicker({
//				 language:'zh-CN',
//	    	 format: 'yyyy-mm-dd',
//	    	 todayHighlight: 1,
//	    	 startView:2,
//	    	 minView:2,
//	    	 autoclose:1,
//	    	 bootcssVer:3
//				});
			
			datePicker.on('changeDate',function(ev){
				console.info('ev',ev);
			});
		}
	}
}]);



sugarfreeApp.directive('tabFactContent',['$log','$window',function($log,$window) {
	var log = true;
	return {
		restrict:'AE',
		replace:true,
		scope:{
			subtracted:'@'
		},
		link:function(scope,element,attrs){
//			$log.info('scope',scope);
//			$log.info('element',element);
//			$log.info('attrs',attrs);
//			$log.info('$window',$window);
			scope.onResize = function(){
				var wHeight = angular.element($window).height();
				var subtracted = scope.subtracted || 170;
				var eleHeight = wHeight - subtracted;
				angular.element('.tab-content').attr('style','height:'+ eleHeight +'px;overflow-y:auto');
			};
			scope.onResize();
			angular.element($window).bind('resize',function(){
				scope.onResize();
			});
		}
	}
}]);

//is test delay delete
sugarfreeApp.directive('tableBody',['$log','$window',function($log,$window) {
	var log = true;
	return {
		restrict:'AE',
		replace:true,
		scope:{
			subtracted:'@',
			fixed:'@'
		},
		link:function(scope,element,attrs){
			scope.onResize = function(){
				var wHeight = angular.element($window).height();
				var subtracted = scope.subtracted || 190;
				var eleHeight = wHeight - subtracted;
				angular.element(element).css("height",eleHeight + "px");
				angular.element(element).css("overflow-y","auto");
			};
			if(scope.fixed){
				scope.onResize();
				angular.element($window).bind('resize',function(){
					scope.onResize();
				});
			}
		}
	}
}]);


sugarfreeApp.directive('dragBox',['$log','$window','$document',function($log,$window,$document) {
	var log = true;
	return {
		restrict:'AE',
		replace:true,
		scope:{
			drag:'@'
		},
		link:function(scope,element,attrs){
			var drag = scope.drag || false;
			if(drag){
				var originX,originY,step=true; 
				angular.element(element).mousedown(function(e){
					  originX = e.offsetX ;
						originY = e.offsetY ;
						step = true;
						angular.element(element).css('cursor','move');
						angular.element($document).mousemove(function(e){
							var wWidth = angular.element($window).width();
							var wHeight = angular.element($window).height();
							var eleWidth = parseFloat(angular.element(element).css('width').replace('px',''));
							var eleHeight = parseFloat(angular.element(element).css('height').replace('px',''));
							
							var subX = e.offsetX - originX;
							var subY = e.offsetY - originY;
							var eleLeft = parseFloat(angular.element(element).css('left').replace('px',''));
							var eleRight = wWidth - eleLeft - eleWidth;
							var eleTop = parseFloat(angular.element(element).css('top').replace('px',''));
							var eleBottom = wHeight - eleTop - eleHeight;
							

//							console.info('subX',subX);
//							console.info('subY',subY);
//							console.info('eleLeft',eleLeft);
//							console.info('eleRight',eleRight);
//							console.info('eleTop',eleTop);
//							console.info('eleBottom',eleBottom);

								if(subX < 0 && eleLeft > 0 || subX > 0 && eleRight > 0){
									angular.element(element).css('left',(eleLeft + subX) + 'px');
								}
								
								if(subY < 0 && eleTop > 0 || subY > 0 && eleBottom > 0){
									angular.element(element).css('top',(eleTop + subY) + 'px');
								}
								
						});
						
						angular.element($document).mouseout(function(e){
								console.info('鼠标移出',e);
								angular.element(element).css('cursor','auto');
								angular.element(this).unbind("mousemove"); 
						});
				});
				
				angular.element($document).mouseup(function(e){
						angular.element(element).css('cursor','auto');
						angular.element(this).unbind("mousemove"); 
				});
			}
		}
	}
}]);


sugarfreeDirectives.run(['$templateCache', function ($templateCache) {
	$templateCache.put('sf-confirm/offEdit.html', '<div id="operation_box"  class="confirm_box">' +
					   '<h1><img src="images/popup_01.png" /></h1>'	+
					   '<div ng-transclude></div>'	+
					   '<div class="confirm_operate">'	+
					   '<button class="btn btn-danger fl" ng-click="optConfirm();setTopParclose(false);">确定</button>'	+
					   '<button class="btn btn-default fr" ng-click="optCancel();">取消</button>'	+
					   '</div>'
	);
	
	
	
	$templateCache.put('sf-confirm/delete.html', '<div id="operation_box"  class="confirm_box">' +
			   '<h1><img src="images/popup_02.png" /></h1>'	+
			   '<div ng-transclude></div>'	+
			   '<div class="confirm_operate">'	+
			   '<button class="btn btn-danger fl" ng-click="optConfirm();setTopParclose(false);">确定</button>'	+
			   '<button class="btn btn-default fr" ng-click="optCancel();">取消</button>'	+
			   '</div>'
	);
	
	$templateCache.put('sf-template/process.html', '<div class="sf_process">{{processText}}</div>');


	//No use
	$templateCache.put('sf-template/timepicker.html',
		'<div class="form-group">' +
		//'<label for="dtp_input3" class="col-md-2 control-label">Time Picking</label>' +    
		'<div class="input-group date form_time col-md-5" data-date="" data-date-format="hh:ii" data-link-field="dtp_input3" data-link-format="hh:ii">' +    
		'<input class="form-control" size="16" type="text" value="" readonly>' +        
		'<span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>' +        
		'<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span></span>' +		
		'</div>' +    
		'<input type="hidden" id="" value="dtp_input3" /><br/>'+
		'</div>'
	);
}]);
